package com.xxlie.auth.config;

import com.xxlie.auth.common.exception.LBLException;
import com.xxlie.auth.common.exception.LBLHandlerException;
import com.xxlie.auth.common.exception.LBLValidateException;
import com.xxlie.auth.common.exception.enums.HandlerExceptionEnums;
import com.xxlie.core.model.View;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理.
 *
 * @author xxlie.com
 * @date 2017年6月26日
 */
@ControllerAdvice(basePackages = "com.xxlie.*")
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * appKey安全处理
     *
     * @param exception {LBLValidateException}
     * @param response  {HttpServletResponse}
     */
    @ExceptionHandler(LBLValidateException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public View<Void> validateExceptionResponse(LBLValidateException exception, HttpServletResponse response) {

        logger.error("全局异常:{}", exception.getMessage(), exception);

        return View.of(exception.getErrorCode(), exception.getMessage());
    }

    @ExceptionHandler(LBLHandlerException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public View<Void> handlerExceptionResponse(LBLHandlerException exception, HttpServletResponse response) {

        logger.error("全局异常:{}", exception.getMessage(), exception);

        return View.of(exception.getErrorCode(), exception.getMessage());

    }

    @ExceptionHandler(LBLException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public View<Void> ecpExceptionResponse(LBLException exception, HttpServletResponse response) {

        logger.error("全局异常:{}", exception.getMessage(), exception);

        return View.of(exception.getErrorCode(), exception.getMessage());

    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public View<Void> exceptionResponse(Exception exception, HttpServletResponse response) {

        logger.error("全局异常:{}", exception.getMessage(), exception);

        return View.of(HandlerExceptionEnums.HANDLER_SERVER_ERROR.getCode(), exception.getMessage());

    }

}
